package Huihu.src.chat;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class Talksend implements Runnable{
    DatagramSocket socket=null;
    BufferedReader bufferedReader=null;

    private int fromPort;
    private String toIP;
    private int toPort;

    public Talksend(int fromPort, String toIP, int toPort) {
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;

        try{
            socket=new DatagramSocket(fromPort);
            bufferedReader=new BufferedReader(new InputStreamReader(System.in));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        //发送数据
        while (true) {
            try{
                String str = bufferedReader.readLine();
                DatagramPacket packet = new DatagramPacket(str.getBytes(), 0, str.getBytes().length, new InetSocketAddress(this.toIP, this.toPort));
                socket.send(packet);
                if (str.equals("byte")) {
                    break;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
